package com.ikun.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;


@Component
/**
 * 文件上传的工具类
 */
public class UploadUtil {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    //存储到oss对象的哪个空间
    String bucketName = "information-system";
    // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
    String region = "cn-beijing";
    /**
     * 单独上传一个文件
     * @param file 上传的文件
     */
    public String uploadFile(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {


        // 1.从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        //2.获取上传文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //3.获取文件路径
        String filePath = file.getOriginalFilename();
        //4.使文件名字具有唯一的标识
        String objectName = UUID.randomUUID() + filePath.substring(filePath.lastIndexOf('.'));
        //5. 创建OSSClient实例:创建oss对象的客户
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        //6.返回文件路径
        String resultUrl=null;
        try {

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //获取并且返回存储在服务器的图片路径
            System.out.println("上传成功：图片路径为："+"https://"+bucketName+"."+endpoint.substring(8)+ "/" + objectName);
            resultUrl="https://"+bucketName+"."+endpoint.substring(8)+ "/" + objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return resultUrl;
    }
    public String uploadFile(String filePath) throws com.aliyuncs.exceptions.ClientException, FileNotFoundException {


        // 1.从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();


        // 2.获取上传文件的输入流
        InputStream inputStream = new FileInputStream(filePath);

        // 3.获取文件路径
        String fileName = new File(filePath).getName();
        //4.使文件名字具有唯一的标识
        String objectName = UUID.randomUUID() + filePath.substring(filePath.lastIndexOf('.'));
        //5. 创建OSSClient实例:创建oss对象的客户
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        //6.返回文件路径
        String resultUrl=null;
        try {

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //获取并且返回存储在服务器的图片路径
            System.out.println("上传成功：图片路径为："+"https://"+bucketName+"."+endpoint.substring(8)+ "/" + objectName);
            resultUrl="https://"+bucketName+"."+endpoint.substring(8)+ "/" + objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return resultUrl;
    }
}
